﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace WpfAppHost
{
    class WaitHandleNotifier
    {
        public event EventHandler WaitHandleSet;

        private bool _running = true;
        private Thread daemon;

        public WaitHandleNotifier(WaitHandle handle)
        {
            this.WaitHandle = handle;
            daemon = new Thread(ThreadStart);
            daemon.Start();
        }

        public void Stop()
        {
            _running = false;
        }

        private void ThreadStart(object state)
        {
            bool set = false;

            while (_running)
            {
                set = WaitHandle.WaitOne(1000);

                if (set)
                {
                    if (WaitHandleSet != null)
                        WaitHandleSet(this, EventArgs.Empty);
                }
            }
        }

        public WaitHandle WaitHandle
        {
            private set;
            get;
        }
    }
}
